﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace DataAdapter
{
    public static class StreamingDataAdapter
    {
        private const string ConnectionString =
            @"Data Source=(local);Initial Catalog=ProjectDB;Integrated Security=True; Min Pool Size=10";

        public static void ExecuteNonQuery(string commandText, Dictionary<string, object> parameters)
        {
            using (var connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = commandText;
                    if (parameters != null)
                    {
                        foreach (var parameter in parameters)
                        {
                            command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                        }
                    }
                    command.ExecuteNonQuery();
                }
            }
        }

        public static DataTable ExecuteQuery(string commandText, Dictionary<string, object> parameters)
        {
            using (var connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = commandText;
                    if (parameters != null)
                    {
                        foreach (var parameter in parameters)
                        {
                            command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                        }
                    }
                    var data = new DataTable();
                    data.Load(command.ExecuteReader());
                    return data;
                }
            }
        }

        public static IDataReader ExecuteQueryReader(string commandText, Dictionary<string, object> parameters)
        {
            var connection = new SqlConnection(ConnectionString);
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = commandText;
                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                    }
                }
                return command.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }

    }

}
